package nginx

import (
	"ginx/config"
	"github.com/xgfone/ngconf"
	"os"
	"strconv"
	"strings"
)

type ConfigController struct {
}

func (c *ConfigController) Init(path string) (config.Config, error) {

	plain, err := os.ReadFile(path)
	if err != nil {
		panic("读取文件失败！")
	}
	context := string(plain)
	context = strings.Replace(context, "\r\n", "\n", -1)
	root, err := ngconf.Decode(context)
	if err != nil {
		panic(err)
	}
	var result config.Config
	result.Events = config.Events{}

	// http
	httpNode := root.Get("http")[0]
	// var serverList []config.Server
	serverList := make([]config.Server, 0)
	// 填充serverList
	for _, serverNode := range httpNode.Get("server") {
		server := config.Server{}
		port, err := strconv.Atoi(serverNode.Get("listen")[0].Args[0])
		if err != nil {
			panic("listen后面需要是数值！")
		}
		server.Listen = port
		server.ServerName = serverNode.Get("server_name")[0].Args[0]
		var locationList []config.Location
		// 创建server
		// 填充locationList
		for _, locationNode := range serverNode.Get("location") {
			locationName := locationNode.Args[0]
			location := config.Location{LocationName: locationName}
			locationList = append(locationList, location)
		}
		server.LocationList = locationList
		serverList = append(serverList, server)
	}
	result.Http = config.Http{ServerList: serverList}

	return result, nil

}
